package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.AsyncDimFunction;
import com.atguigu.Func.MyWindowFunction;
import com.atguigu.Util.ClickHouseUtil;
import com.atguigu.Util.MyKafkaUtil;
import com.atguigu.bean.TradeSkuOrderBean;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @author hjy
 * @create 2023/3/20 20:28
 */
//数据流:web/app -> 业务服务器(Mysql) -> Maxwell -> Kafka(ODS) -> FlinkApp -> Kafka(DWD) -> FlinkApp -> ClickHouse(DWS)
//程 序:Mock -> Mysql -> Maxwell -> Kafka(ZK) -> Dwd03_TradeOrderDetail -> Kafka(ZK) -> Dws09TradeSkuOrderWindow(Redis,Phoenix) -> ClickHouse(ZK)
public class Dws09_TradeSkuOrderWindow {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall-flink/check");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HADOOP_USER_NAME","atguigu");
        //todo 2 从kafka(dwd_trade_order_detail)读数据
        String topic ="dwd_trade_order_detail";
        String groupID="dws_trade_sku_order_window";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupID));
        //todo 3 过滤数据并转为JSONObj
        SingleOutputStreamOperator<JSONObject> jsonObjectDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    out.collect(JSONObject.parseObject(value));
                }
            }
        });
        //todo 4 获取waterMark
        SingleOutputStreamOperator<JSONObject> jsonObjWithWM = jsonObjectDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("create_time");
                    }
                })));
        //todo 5 按照id分组
        KeyedStream<JSONObject, String> keyedByIdDS = jsonObjWithWM.keyBy(value -> value.getString("id"));
        //todo 6 转化为javaBean对象 并去重
        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanDS = keyedByIdDS.flatMap(new RichFlatMapFunction<JSONObject, TradeSkuOrderBean>() {
            private ValueState<String> existState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlCfg = StateTtlConfig.newBuilder(Time.seconds(5))
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                        .build();
                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("exist", String.class);
                valueStateDescriptor.enableTimeToLive(ttlCfg);
                existState = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradeSkuOrderBean> out) throws Exception {
                String exist = existState.value();
                if (exist == null) {
                    existState.update("1");
                    BigDecimal orderAmount = value.getBigDecimal("split_total_amount");
                    BigDecimal activityAmount = value.getBigDecimal("split_activity_amount");
                    BigDecimal couponAmount = value.getBigDecimal("split_coupon_amount");
                    BigDecimal originalAmount = value.getBigDecimal("split_original_amount");
                    if (activityAmount == null) {
                        activityAmount = new BigDecimal("0.0");
                    }
                    if (couponAmount == null) {
                        couponAmount = new BigDecimal("0.0");
                    }

                    out.collect(TradeSkuOrderBean.builder()
                            .skuId(value.getString("sku_id"))
                            .skuName(value.getString("sku_name"))
                            .orderAmount(orderAmount)
                            .originalAmount(originalAmount)
                            .activityAmount(activityAmount)
                            .couponAmount(couponAmount)
                            .build());
                }
            }
        });
        //todo 7 分组开窗聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> reduceDS = tradeSkuOrderBeanDS.keyBy(TradeSkuOrderBean::getSkuId)
                .window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<TradeSkuOrderBean>() {
                    @Override
                    public TradeSkuOrderBean reduce(TradeSkuOrderBean value1, TradeSkuOrderBean value2) throws Exception {
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                        value1.setActivityAmount(value1.getActivityAmount().add(value2.getActivityAmount()));
                        value1.setCouponAmount(value1.getCouponAmount().add(value2.getCouponAmount()));
                        return value1;
                    }
                }, new WindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TradeSkuOrderBean> input, Collector<TradeSkuOrderBean> out) throws Exception {
                        TradeSkuOrderBean next = input.iterator().next();
                        out.collect(MyWindowFunction.getJavabeanFields(next, window));
                    }
                });

        //todo 8 关联维表
        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithSKUInfo = AsyncDataStream.unorderedWait(reduceDS, new AsyncDimFunction<TradeSkuOrderBean>("DIM_SKU_INFO") {
            @Override
            public void joinDimInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                input.setTrademarkId(dimInfo.getString("TM_ID"));
                input.setSpuId(dimInfo.getString(
"SPU_ID"));
                input.setCategory3Id(dimInfo.getString("CATEGORY3_ID"));
            }
            @Override
            public String getKey(TradeSkuOrderBean input) {
                return input.getSkuId();
            }
        }, 60, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithSPUInfo = AsyncDataStream.unorderedWait(tradeSkuOrderBeanWithSKUInfo, new AsyncDimFunction<TradeSkuOrderBean>("DIM_SPU_INFO") {
            @Override
            public void joinDimInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                input.setSpuName(dimInfo.getString("SPU_NAME"));
            }

            @Override
            public String getKey(TradeSkuOrderBean input) {
                return input.getSpuId();
            }
        }, 60, TimeUnit.SECONDS);


        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithTradeMark = AsyncDataStream.unorderedWait(tradeSkuOrderBeanWithSPUInfo, new AsyncDimFunction<TradeSkuOrderBean>("DIM_BASE_TRADEMARK") {
            @Override
            public void joinDimInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                input.setTrademarkName(dimInfo.getString("TM_NAME"));
            }

            @Override
            public String getKey(TradeSkuOrderBean input) {
                return input.getTrademarkId();
            }
        }, 60, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithCategory3 = AsyncDataStream.unorderedWait(tradeSkuOrderBeanWithTradeMark, new AsyncDimFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY3") {
            @Override
            public void joinDimInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                input.setCategory3Name(dimInfo.getString("NAME"));
                input.setCategory2Id(dimInfo.getString("CATEGORY2_ID"));
            }

            @Override
            public String getKey(TradeSkuOrderBean input) {
                return input.getCategory3Id();
            }
        }, 60, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithCategory2 = AsyncDataStream.unorderedWait(tradeSkuOrderBeanWithCategory3, new AsyncDimFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY2") {
            @Override
            public void joinDimInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                input.setCategory2Name(dimInfo.getString("NAME"));
                input.setCategory1Id(dimInfo.getString("CATEGORY1_ID"));
            }

            @Override
            public String getKey(TradeSkuOrderBean input) {
                return input.getCategory2Id();
            }
        }, 60, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithCategory1DS = AsyncDataStream.unorderedWait(tradeSkuOrderBeanWithCategory2, new AsyncDimFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY1") {
            @Override
            public void joinDimInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                input.setCategory1Name(dimInfo.getString("NAME"));
            }

            @Override
            public String getKey(TradeSkuOrderBean input) {
                return input.getCategory1Id();
            }
        }, 60, TimeUnit.SECONDS);

        //TODO 9.将数据写出
        tradeSkuOrderBeanWithCategory1DS.print("tradeSkuOrderWithCategory1DS>>>>>>>>");
        tradeSkuOrderBeanWithCategory1DS.addSink(ClickHouseUtil.getSinkFunction("insert into dws_trade_sku_order_window values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));

        //TODO 10.启动
        env.execute("Dws09TradeSkuOrderWindow");


    }
}
